<template>
  <div class="chat-view">
    <div class="view-body">
      <div class="wxchat-container" style="background-color: rgb(239, 239, 239);">
        <div id="window-view-container" class="window">
            <div class="title">聊天室</div>
            <div id="scrollLoader-container" class="container-main">
                <div>
                    <div class="message">
                      <ul>
                        <li v-for="(item, idx) in chatList" :key="idx" :class="item.style === 'right' ? 'an-move-right' : 'an-move-left'">
                          <div v-if="item.style === 'center'">
                            <p class="time"><span>{{ item.msg }} {{ getFormatdate(item.time) }}</span></p>
                          </div>
                          <div v-else>
                            <p class="time"><span>{{ getFormatdate(item.time) }}</span></p>
                            <div class="main" :class="item.style === 'right' ? ' self' : ''">
                              <img :title="item.nickname" width="45" height="45" src="../../assets/images/avatar/avatar2.png" class="avatar">
                              <div v-show="item.style !== 'right'">{{ item.nickname }}</div>
                              <div v-if="item.type === 'file'" class="text">
                                <div>{{ item.msg }}</div>
                                <div class="text-action">
                                  <span @click="handleDownloadFile(item)" class="action-item">下载</span>
                                </div>
                              </div>
                              <div v-else-if="item.type === 'image'" class="text">
                                <div><img :src="item.code" class="static-emotion-gif" style="vertical-align: middle" /></div>
                                <div class="text-action">
                                  <span @click="handleDownloadFile(item)">下载</span>
                                </div>
                              </div>
                              <div v-else class="text"><pre>{{ item.msg }}</pre></div>
                            </div>
                          </div>
                        </li>
                        <!-- <li class="an-move-left">
                            <p class="time"><span>2024/9/23 22:03:30</span></p>
                            <div class="main">
                              <img width="45" height="45" src="../../assets/images/avatar/avatar2.png" class="avatar">
                              <div class="text">向上滚动加载第 2 条！</div>
                            </div>
                        </li>
                        <li class="an-move-right">
                            <p class="time"><span
                                  >2024/9/23 22:03:30</span></p>
                            <div class="main self"><img
                                    width="45" height="45" src="../../assets/images/avatar/avatar1.png"
                                    class="avatar">
                                <div class="text">向上滚动加载第 2 条！</div>
                            </div>
                        </li>
                        <li class="an-move-left">
                            <p class="time"><span
                                  >2024/9/23 21:44:53</span></p>
                            <div class="main"><img
                                    width="45" height="45" src="../../assets/images/avatar/avatar2.png"
                                    class="avatar">
                                <div class="text">向上滚动加载第 1 条！</div>
                            </div>
                        </li>
                        <li class="an-move-right">
                            <p class="time"><span
                                  >2024/9/23 21:44:53</span></p>
                            <div class="main self"><img
                                    width="45" height="45" src="../../assets/images/avatar/avatar1.png"
                                    class="avatar">
                                <div class="text">向上滚动加载第 1 条！</div>
                            </div>
                        </li>
                        <li class="an-move-right">
                            <p class="time"><span
                                  >2024/9/23 21:43:42</span></p>
                            <div class="main self"><img
                                    width="45" height="45" src="../../assets/images/avatar/avatar1.png"
                                    class="avatar">
                                <div class="text">你好!!<img
                                        class="static-emotion-gif" style="vertical-align: middle"
                                        src="../../assets/images/avatar/13.gif"></div>
                            </div>
                        </li>
                        <li class="an-move-left">
                            <p class="time"><span
                                  >2024/9/23 21:43:42</span></p>
                            <div class="main"><img
                                    width="45" height="45" src="../../assets/images/avatar/avatar2.png"
                                    class="avatar">
                                <div class="text">你也好。<img
                                        class="static-emotion-gif" style="vertical-align: middle"
                                        src="../../assets/images/avatar/6.gif"></div>
                            </div>
                        </li>
                        <li class="an-move-right">
                            <p class="time"><span
                                  >2024/9/23 21:43:42</span></p>
                            <div class="main self"><img
                                    width="45" height="45" src="../../assets/images/avatar/avatar1.png"
                                    class="avatar">
                                <div class="text">这是我的简历头像：</div>
                            </div>
                        </li>
                        <li class="an-move-right">
                            <p class="time"><span
                                  >2024/9/23 21:43:42</span></p>
                            <div class="main self"><img
                                    width="45" height="45" src="../../assets/images/avatar/avatar1.png"
                                    class="avatar">
                                <div class="text"><img
                                        src="../../assets/images/avatar/wyz.jpg" alt="聊天图片"
                                        class="image"></div>
                            </div>
                        </li>
                        <li class="an-move-left">
                            <p class="time"><span
                                  >2024/9/23 21:43:42</span></p>
                            <div class="main"><img
                                    width="45" height="45" src="../../assets/images/avatar/avatar2.png"
                                    class="avatar">
                                <div class="text">你开心就好。<img
                                        class="static-emotion-gif" style="vertical-align: middle"
                                        src="../../assets/images/avatar/0.gif"></div>
                            </div>
                        </li>
                        <li class="an-move-left">
                            <p class="time"><span
                                  >2024/9/23 21:44:50</span></p>
                            <div class="main"><img
                                    width="45" height="45" src="../../assets/images/avatar/avatar2.png"
                                    class="avatar">
                                <div class="text">向下滚动加载第 1 条！</div>
                            </div>
                        </li>
                        <li class="an-move-right">
                            <p class="time"><span
                                  >2024/9/23 21:44:50</span></p>
                            <div class="main self"><img
                                    width="45" height="45" src="../../assets/images/avatar/avatar1.png"
                                    class="avatar">
                                <div class="text">向下滚动加载第 1 条！</div>
                            </div>
                        </li>
                        <li class="an-move-left">
                            <p class="time"><span
                                  >2024/9/23 21:44:52</span></p>
                            <div class="main"><img
                                    width="45" height="45" src="../../assets/images/avatar/avatar2.png"
                                    class="avatar">
                                <div class="text">向下滚动加载第 2 条！</div>
                            </div>
                        </li>
                        <li class="an-move-right">
                            <p class="time"><span
                                  >2024/9/23 21:44:52</span></p>
                            <div class="main self"><img
                                    width="45" height="45" src="../../assets/images/avatar/avatar1.png"
                                    class="avatar">
                                <div class="text">向下滚动加载第 2 条！</div>
                            </div>
                        </li>
                        <li class="an-move-left">
                            <p class="time"><span
                                  >2024/9/23 22:02:14</span></p>
                            <div class="main"><img
                                    width="45" height="45" src="../../assets/images/avatar/avatar2.png"
                                    class="avatar">
                                <div class="text">向下滚动加载第 3 条！</div>
                            </div>
                        </li>
                        <li class="an-move-right">
                            <p class="time"><span
                                  >2024/9/23 22:02:14</span></p>
                            <div class="main self"><img
                                    width="45" height="45" src="../../assets/images/avatar/avatar1.png"
                                    class="avatar">
                                <div class="text">向下滚动加载第 3 条！</div>
                            </div>
                        </li> -->
                      </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
    </div>
    <div class="view-control">
      <div class="control-bar">
        <span class="bar-item">
          <el-upload action="/"
            :limit="1000"
            :file-list="fileList"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="handleChangeFile"
            multiple>
            <i class="el-icon-folder-opened item-file"></i>
          </el-upload>
        </span>
        <span class="bar-item">
          <el-upload action="/"
            :limit="1000"
            :file-list="imageList"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="handleChangeImage"
            accept="image/png,image/jpg,image/jpeg,image/gif,image/webp"
            multiple>
            <i class="el-icon-picture item-image"></i>
          </el-upload>
        </span>
      </div>
      <div class="control-input">
        <el-input v-model="sendMsg" type="textarea" rows="6" placeholder="请输入内容"></el-input>
      </div>
      <div class="control-action">
        <span></span>
        <el-button @click="handleSend" type="primary" size="small">发送</el-button>
      </div>
    </div>
    <el-dialog title="输入昵称" :visible="dialogVisible" width="30%">
      输入昵称:
      <el-input v-model="nickname"> </el-input>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="login" size="small">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { dater, strer, filer } from '@daelui/dogjs/dist/components'
import { io } from 'socket.io-client'
let rules = window.application.dchat.mode.rules || []
let socketPort = (rules.find(item => item.rule === 'socketPort') || {}).value

export default {
  data() {
    return {
      socket: null,
      sendMsg: '',
      nickname: '',
      dialogVisible: false,
      chatList: [],
      fileList: [],
      imageList: []
    }
  },

  created() {
    let hostname = location.hostname
    this.socket = io('ws://' + hostname + ':' + socketPort, {
      transports: ["websocket"],
    })
    // 建立连接
    this.socket.on('connect', () => {
      console.log('建立连接'); // ojIckSD2jqNzOqIrAGzL
    })
    // 登录
    this.socket.on('logged', (data) => {
      this.severLog(data)
    })
    // 退出
    this.socket.on('logout', (data) => {
      this.severLog(data)
    })
    // 接收消息
    this.socket.on("response_chat", (data) => {
      this.severChat(data)
    })
    // 服务端从客户端拉取文件
    this.socket.on('file_pull_from_client', (data) => {
      this.filePushToServer(data)
    })
    // 服务端向客户端推送文件
    this.socket.on('file_push_to_client', (buffer, data) => {
      this.createFileFromBuffer(buffer, data.filename)
    })
    // 初始化用户
    this.initUser()
  },

  mounted() {},

  beforeDestroy() {
    // 断开连接
    this.socket.disconnect()
  },

  methods: {
    severLog({ nickname, isLogin, wsid }) {
      let state = isLogin ? "进入" : "离开";
      let msg = `${nickname} ${state}聊天室`;
      this.addChat({
        msg,
        style: "center"
      })
      this.$store.state.user.userid = wsid
    },
    // 发送
    handleSend() {
      let msg = this.sendMsg
      this.addChat({
        msg,
        nickname: this.nickname,
        style: "right"
      })
      this.sendMsg = ''
      this.send({ msg })
    },
    // 发送至服务端
    send (data) {
      this.socket.emit('chat', data)
    },
    // 接收信息
    severChat(data) {
      this.addChat(Object.assign(data, {
        style: "left"
      }))
    },
    // 插入聊天信息
    addChat(data) {
      data.time = data.time || Date.now()
      this.chatList.push(data)
    },
    // 初始化用户
    initUser () {
      let uid = strer.urid(6)
      this.nickname = uid
      this.$store.state.user.nickname = uid
      this.socket.emit('login', this.nickname)
    },
    getNikname() {
      let nickname = this.$store.state.user?.nickname
      if (nickname) {
        this.dialogVisible = false
        this.socket.emit("login", nickname)
      }
      this.dialogVisible = !nickname
      this.nickname = nickname
    },
    // 登录
    login() {
      if (!this.nickname) {
        this.$notify({
          message: "昵称不为空"
        })
        return
      }
      this.socket.emit("login", this.nickname)
      this.dialogVisible = false
    },
    // 格式化日期
    getFormatdate (time) {
      return dater.format(time)
    },
    // 上传文件
    handleChangeFile (file) {
      this.addChat({
        msg: file.name,
        size: file.size,
        file: file.raw,
        fid: file.uid,
        type: 'file',
        nickname: this.nickname,
        style: "right"
      })
      this.send({
        msg: file.name,
        type: 'file',
        fid: file.uid
      })
    },
    // 下载文件
    handleDownloadFile (node) {
      this.socket.emit('file_request_download', {
        msg: node.msg,
        type: node.type,
        fid: node.fid,
        userid: this.$store.state.user.userid
      })
    },
    // 上传图片
    handleChangeImage (file) {
      filer.fileToBase64(file.raw).then(text => {
        this.addChat({
          msg: file.name,
          size: file.size,
          file: file.raw,
          fid: file.uid,
          type: 'image',
          code: text,
          nickname: this.nickname,
          style: "right"
        })
        this.send({
          msg: file.name,
          code: text,
          type: 'image',
          fid: file.uid
        })
      })
    },
    // 传输文件至服务端
    filePushToServer(data) {
      let node = this.chatList.find(item => item.fid === data.fid)
      if (node && node.file) {
        const reader = new FileReader()
        reader.onload = (event) => {
          const buffer = event.target.result
          this.socket.emit('file_push_to_server', buffer, {
            filename: node.file.name,
            wsid: data.wsid
          })
        }
        reader.readAsArrayBuffer(node.file)
      }
    },
    // 假设buffer是一个Buffer实例，代表文件的数据
    createFileFromBuffer(buffer, fileName) {
      // 创建一个Blob实例，类型根据文件确定，这里假设是一个文本文件
      const blob = new Blob([buffer], { type: 'text/plain' });
      // 创建一个指向Blob的URL
      const fileUrl = URL.createObjectURL(blob);
    
      // 创建一个a标签用于触发下载
      const downloadLink = document.createElement('a');
      downloadLink.href = fileUrl;
      downloadLink.download = fileName; // 设置下载文件名
      document.body.appendChild(downloadLink);
    
      // 触发下载
      downloadLink.click();
    
      // 清理
      document.body.removeChild(downloadLink);
      URL.revokeObjectURL(fileUrl);
    }
  }
}
</script>
 
<style lang="less" scoped>
.chat-view {
  display: flex;
  flex-direction: column;
  width: 100vw;
  height: 100vh;
}
.view-body {
  position: relative;
  flex: 1;
  background-color: #fff;
  color: #333;
  .center {
    text-align: center;
  }
  .left {
    text-align: left;
  }
  .right {
    text-align: right;
  }
  pre {
    white-space: break-spaces;
  }
}
ul {
  margin: 0;
  padding: 0;
  list-style: none;
}
.view-control {
  padding: 0 8px 8px;
  border-top: 1px solid #DCDFE6;
  .control-bar {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    height: 40px;
  }
  .bar-item {
    margin-right: 4px;
    & + .bar-item {
      font-size: 24px;
    }
    .item-file {
      font-size: 24px;
    }
  }
}
.control-input {
  padding-bottom: 8px;
}
.control-action {
  display: flex;
  justify-content: space-between;
}
.text-action {
  padding-top: 4px;
  line-height: 14px;
  font-size: 12px;
  color: #409EFF;
  cursor: pointer;
  .action-item {
    margin-right: 4px;
  }
}


.wxchat-container {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 100;
  overflow: hidden
}

.shadow {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 100;
    width: 100%;
    height: 100%;
    background: #000;
    opacity: .2
}

.window {
    background: #f5f5f5;
    overflow: hidden;
    position: relative;
    padding: 0;
    width: 100%;
    height: 100%;
    z-index: 101;
    box-shadow: 1px 1px 20px -5px #000;
}

.w100 {
    width: 100%
}

.mt5 {
    margin-top: 5px
}

.mt10 {
    margin-top: 10px
}

.mt20 {
    margin-top: 20px
}

.mb10 {
    margin-bottom: 10px
}

.mb20 {
    margin-bottom: 20px
}

.fs0 {
    font-size: 0
}

.title {
    background: #324156;
    text-align: center;
    color: #fff;
    width: 100%;
    height: 50px;
    line-height: 50px;
    font-size: 14px
}

.loading,
.no-more {
    text-align: center;
    color: #b0b0b0;
    line-height: 100px
}

.no-more {
    line-height: 60px
}

.pull-right {
    float: right
}

.link-line {
    text-decoration: underline
}

.message {
    padding: 10px 15px;
    background-color: #f5f5f5
}

.message li {
    margin-bottom: 15px;
    left: 0;
    position: relative;
    display: block
}

.message .time {
    margin: 10px 0;
    text-align: center
}

.message .text {
    display: inline-block;
    position: relative;
    padding: 0 10px;
    max-width: calc(100% - 75px);
    min-height: 35px;
    line-height: 2.1;
    font-size: 15px;
    padding: 6px 10px;
    text-align: left;
    word-break: break-all;
    background-color: #fff;
    color: #000;
    border-radius: 4px;
    box-shadow: 0 1px 7px -5px #000
}

.message .avatar {
    float: left;
    margin: 0 10px 0 0;
    border-radius: 3px;
    background: #fff
}

.message .time>span {
    display: inline-block;
    padding: 0 5px;
    font-size: 12px;
    color: #fff;
    border-radius: 2px;
    background-color: #dadada
}

.message .system>span {
    padding: 4px 9px;
    text-align: left
}

.message .text:before {
    content: " ";
    position: absolute;
    top: 9px;
    right: 100%;
    border: 6px solid transparent;
    border-right-color: #fff
}

.message .self {
    text-align: right
}

.message .self .avatar {
    float: right;
    margin: 0 0 0 10px
}

.message .self .text {
    background-color: #9eea6a
}

.message .self .text:before {
    right: inherit;
    left: 100%;
    border-right-color: transparent;
    border-left-color: #9eea6a
}

.message .image {
    max-width: 200px
}

img.static-emotion-gif,
img.static-emotion {
    vertical-align: middle !important
}

.an-move-left {
    left: 0;
    animation: moveLeft-data-v-614b8646 .7s ease;
    -webkit-animation: moveLeft-data-v-614b8646 .7s ease
}

.an-move-right {
    left: 0;
    animation: moveRight-data-v-614b8646 .7s ease;
    -webkit-animation: moveRight-data-v-614b8646 .7s ease
}

.bgnone {
    background: none
}

@keyframes moveRight-data-v-614b8646 {
    0% {
        left: -20px;
        opacity: 0
    }

    to {
        left: 0;
        opacity: 1
    }
}

@-webkit-keyframes moveRight {
    0% {
        left: -20px;
        opacity: 0
    }

    to {
        left: 0;
        opacity: 1
    }
}

@keyframes moveLeft-data-v-614b8646 {
    0% {
        left: 20px;
        opacity: 0
    }

    to {
        left: 0;
        opacity: 1
    }
}

@-webkit-keyframes moveLeft {
    0% {
        left: 20px;
        opacity: 0
    }

    to {
        left: 0;
        opacity: 1
    }
}

@media (max-width:367px) {
    .fzDInfo {
        width: 82%
    }
}
.container-main {
    margin: 0 auto;
    overflow: auto;
    overflow-x: hidden;
    padding: 0;
    height: calc(100% - 50px);
}

.loading {
    width: 100%;
    height: 40px;
    position: relative;
    overflow: hidden;
    text-align: center;
    margin: 5px 0;
    color: #999;
    font-size: 13px
}

.loading-icon {
    color: #707070
}

.loader {
    font-size: 10px;
    margin: 8px auto;
    text-indent: -9999em;
    width: 24px;
    height: 24px;
    border-radius: 50%;
    background: #999;
    background: linear-gradient(90deg, #999 10%, hsla(0, 0%, 100%, 0) 42%);
    position: relative;
    -webkit-animation: load3-data-v-a10a4326 1s infinite linear;
    animation: load3-data-v-a10a4326 1s infinite linear
}

.loader:before {
    width: 50%;
    height: 50%;
    background: #999;
    border-radius: 100% 0 0 0;
    position: absolute;
    top: 0;
    left: 0;
    content: ""
}

.loader:after {
    background: #f5f5f5;
    width: 72%;
    height: 75%;
    border-radius: 68%;
    content: "";
    margin: auto;
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0
}

@-webkit-keyframes load3 {
    0% {
        -webkit-transform: rotate(0deg);
        transform: rotate(0deg)
    }

    to {
        -webkit-transform: rotate(1turn);
        transform: rotate(1turn)
    }
}

@keyframes load3-data-v-a10a4326 {
    0% {
        -webkit-transform: rotate(0deg);
        transform: rotate(0deg)
    }

    to {
        -webkit-transform: rotate(1turn);
        transform: rotate(1turn)
    }
}
</style>
